#ifndef MSGMANAGE_H
#define MSGMANAGE_H

#pragma once

#include <QObject>
#include "model/modelmsg.h"
#include <QSharedPointer>
#include <QVector>
#include "ModelShip.h"
#include "networktask.h"

namespace ns_yht
{

#define MSGMANAGE MsgManage::instance()

    class MsgManage : public QObject
    {
        Q_OBJECT
    private:
        MsgManage();

    public:
        ~MsgManage();
        static MsgManage *instance();

        void bindSignals();
        const QVector<QSharedPointer<ModelMsg>> &msgList(int level) const;
        int getCount(int level) const;
        void getNext2Msg(int level, int &index1, int &index2);

        ModelMsg *getNextMsg();
        ModelMsg *getNextCaution();
        void ensure(ModelMsg *model);
        void ensure();

        void appendPoiAlarm(int poiType);
        void cancelPoiAlarm();

        void appendPoiWarning(int poiType);
        void cancelPoiWarning();

        // void setTts(bool useTts);
        // bool getTts() const;

        void appendDuty_normal();
        void cancelDuty_normal();
        void appendDuty_emergency();
        void cancelDuty_emergency();

        void appendRiskAreaWarning(int atype);
        void cancelRiskAreaWarning(int atype);

        QString getLevelStr(int level);
        static int getLevel(int type);

        // 是否有未解除的消息，包括确认的，用于控灯
        bool hasMsg() const;

        void setNetworkTask(NetworkTask *task);

    public slots:
        void appendDeviceLose(int deviceId);
        void recoverDevice(int deviceId);
        void appendEFenceMsg(const QString &msg);
        void appendDangerousShip(quint64 mmsi, double tcpa, QString name, bool emergency = true);
        void cancelDangerousShip(quint64 mmsi, bool emergency = true);
        void cancelAllShipCollision();

        void autoDangerousShip(quint64 mmsi, bool isEnsure);

        void appendAnchorDragging();
        void cancelAnchorDragging();

        void appendOffroute();
        void cancelOffroute();

        void appendOffrouteCourse();
        void cancelOffrouteCourse();

        void appendNearWaypoint(int index);
        void appendNearDestination();
        void cancelNearWaypoint();
        void appendMeetWaypoint(int index);
        void appendMeetDestination();

        void appendUsermap();
        void cancelUsermap();

        void ensure(int level, int index, bool isEnsured = true);

    signals:
        void newMsg(ModelMsg *model);
        // 紧急报警长时间没有确认，触发外部声音报警
        void emergencyAlarm();
        void ensureToShipManage(quint64 mmsi, bool isEnsured = true);

    private:
        int findMsg(int level, int type, qint64 ID = 0);

        static MsgManage *g_manage;
        QVector<QSharedPointer<ModelMsg>> m_listMessage[3];

        int m_msgIndex[3]{0, 0, 0};

        void timerEvent(QTimerEvent *event) override;
        void save();
        int m_timerId{-1};
        bool m_deviceLost{false};

        NetworkTask *m_networkTask{nullptr};
    };

} // namespace ns_yht

#endif